/**
 * Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */
package com.mbfasttrack.controller;

import com.mbfasttrack.model.Media;
import com.mbfasttrack.service.MediaService;
import com.mbfasttrack.utils.Default;
import com.mongodb.gridfs.GridFSDBFile;
import imageUtil.Image;
import imageUtil.ImageLoader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Marco Berri marcoberri@gmail.com http://tecnicume.blogspot.com
 */
@Controller
public class MediaController extends Base {

    /**
     *
     * @return
     */
    @ModelAttribute("media")
    public Media getMediaObject() {
        return new Media();
    }

    /**
     *
     * @param mediaService
     */
    @Autowired(required = true)
    public void setMediaService(MediaService mediaService) {
        this.mediaService = mediaService;

    }

    /**
     *
     * @param media
     * @param model
     * @return
     */
    @RequestMapping(value = "/media/save", method = RequestMethod.POST)
    public String save(@ModelAttribute("media") Media media, Model model) {

        if (isGuest()) {
            return "redirect:/login";
        }

        org.springframework.security.core.userdetails.User u = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        media = mediaService.add(media, u.getUsername());
        // TO DO - DA CAPiRE - actionService.add(media, u.getUsername(), "add", media.get);
        model.addAttribute("media", media);

        return "response/ok";

    }

    /**
     *
     * @param opts
     * @param type
     * @param id
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/media/{type}/{id}", method = RequestMethod.GET)
    public ModelAndView get(@RequestParam(value = "opts", required = false) String opts, @PathVariable String type, @PathVariable String id, HttpServletResponse response) throws IOException {

        Media media = mediaService.mediaRepository.findOne(id);

        System.err.println("type :" + media.getType());

        if (media.getType().equals(type)) {

            ObjectId obj_id = new ObjectId(media.getFileId().toString());
            GridFSDBFile file = mediaService.getFile(obj_id);

            if (file == null) {
                System.err.println("file == null");
                return null;
            }


            String md5_file = DigestUtils.md5Hex(file.getFilename() + file.getMD5() + opts);
            System.err.println("md5_file :" + md5_file);

            File cache_file = mediaService.getCacheFile(md5_file, type);

            Image image = null;

            System.err.println("cache_file :" + cache_file);

            if (cache_file == null) {

                image = ImageLoader.fromStream(file.getInputStream());

                if (opts != null) {
                    if (opts.indexOf("resized_to_width-") != -1) {
                        opts = opts.replaceAll("resized_to_width-", "");
                        int opts_int = Default.toInt(opts, 100);
                        if (opts_int < image.getWidth()) {
                            image = image.getResizedToWidth(opts_int);
                        }
                    }

                    if (opts.indexOf("resized_to_height-") != -1) {
                        opts = opts.replaceAll("resized_to_height-", "");
                        int opts_int = Default.toInt(opts, 100);
                        if (opts_int < image.getHeight()) {
                            image = image.getResizedToWidth(opts_int);

                        }
                    }

                } else {
                    System.err.println("opts = null");
                }

                //put in cache
                cache_file = mediaService.putCacheFile(md5_file, type, image, "png");

            }



            response.setHeader("Content-Disposition", "attachment; filename=\"" + FilenameUtils.getBaseName(file.getFilename()) + ".png\"");
            response.setContentType("image/png");
            image = ImageLoader.fromFile(cache_file);
            image.writeToStream((OutputStream) response.getOutputStream(), "png");

            return null;

        }
        return null;
    }
}